package com.xyd.wechat.tools;

import com.xyd.wechat.common.ApplicationConfig;
import com.xyd.wechat.vo.TokenVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class VerificationTool {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ApplicationConfig applicationConfig;

    public String signature(TokenVo tokenVo) {
        //参数按字典排序
        List<String> list = new ArrayList<String>();
        list.add(tokenVo.getNonce());
        list.add(tokenVo.getTimestamp());
        list.add(applicationConfig.getWechatToken());
        Collections.sort(list);
        //生成字符串
        StringBuffer content = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            content.append(list.get(i));
        }
        //sha1加密
        String temp = DigestUtils.sha1Hex(content.toString());
        logger.info("sha1加密:{}", temp);
        logger.info("signature:{}", tokenVo.getSignature());
        if (temp.equals(tokenVo.getSignature())) {
            return tokenVo.getEchostr();
        } else {
            return null;
        }
    }
}
